import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import { Toast } from 'vant';

Vue.use(VueRouter)
Vue.use(Toast);

const routes = [
  {
    path: '/',
    redirect: "/home"
  },
  {
    path: '/home',
    name: 'Home',
    component: Home,
    meta: true,
    children: [
      {
        // 子路由的path,要么不加斜杠,要么把前面的路径也写进去  popup    /home/popup
        path: 'popup',
        component: () => import(/* webpackChunkName: "popup" */ '../views/Popup.vue')
      }
    ]
  },
  {
    path: '/topic',
    name: 'Topic',
    meta: true,
    component: () => import(/* webpackChunkName: "topic" */ '../views/Topic.vue')
  },
  {
    path: '/category',
    name: 'Category',
    meta: true,
    component: () => import(/* webpackChunkName: "category" */ '../views/Category.vue')
  },
  {
    path: '/cart',
    name: 'Cart',
    meta: true,
    component: () => import(/* webpackChunkName: "cart" */ '../views/Cart.vue')
  },
  {
    path: '/user',
    name: 'User',
    meta: true,
    component: () => import(/* webpackChunkName: "user" */ '../views/User.vue')
  },
  {
    path: '/detail/:id',
    name: 'Detail',
    component: () => import(/* webpackChunkName: "detail" */ '../views/Details.vue')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 重定向bug修复
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}

// 全局的导航守卫（路由拦截）
router.beforeEach((to, from, next) => {
  if (to.fullPath == '/cart') {
    // 判断有没有token
    let token = localStorage.getItem("token");
    if (token) {
      // 有token进入购物车
      next()
    } else {
      Toast.loading({
        message: '请先登录',
        forbidClick: true,
      })
      setTimeout(() => {
        // 没有token去User页面
        next('/user')
      }, 1500)
    }
  } else {
    next(); // 一个导航守卫中，必须存在唯一的一个有效next()
  }
})

export default router



